package com.hzlh.core.web.controller;


import java.io.File;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.hzlh.core.domain.ImageUploadToFrame;
import com.hzlh.core.domain.UploadedFile;
import com.hzlh.core.service.SystemParameterService;
import com.hzlh.core.service.UploadService;
import com.hzlh.core.utils.FileUtils;
import com.hzlh.core.utils.ImageUtils;



/**
 * 上传公用Action
 * <p>
 */

@Controller
public class UploadController {


	private static final String SCALE = "-scale";

	@Autowired
	@Qualifier("uploadFtpService")
	private UploadService uploadService;

	@Autowired
	private SystemParameterService systemParameterService;

	private void kindeditorOutput(PrintWriter out, UploadedFile uploadedFile, String url) {
		JSONObject obj = new JSONObject();

		obj.put("filename", uploadedFile.getFileUploadedName());// 上传之后的文件名
		obj.put("fileOriginalName", uploadedFile.getFileOriginalName());// 原始文件名
		obj.put("url", url);

		obj.put("error", 0);

		out.println(obj.toString());
		out = null;
	}

	/**
	 * kindeditor中的附件上传
	 * <p>
	 *
	 * @param request
	 * @param out
	 * @param response
	 */
	@RequestMapping(value = { "/kindeditor-accessory-upload" })
	public void kindeditorAccessoryUpload(@RequestParam("imgFile") MultipartFile file, HttpServletRequest request,
			HttpServletResponse response, PrintWriter out) {
		UploadedFile uploadedFile = null;
		String uploadFirstSubDir = null;
		String url = null;// 上传之后的读取url

		uploadFirstSubDir = "kindeditor-accessory";
		uploadedFile = uploadService.uploadFileToUploadDir(uploadFirstSubDir, file);
		url = uploadService.getUploadUrl() + uploadedFile.getReadUrl();

		kindeditorOutput(out, uploadedFile, url);
	}
	
	

	/**
	 * 图片上传器的上传
	 * <p>
	 *
	 * @param request
	 * @param response
	 * @param out
	 */
	@RequestMapping(value = { "/imageUploador-upload" })
	public void imageUploadorUpload(@RequestParam("Filedata") MultipartFile file, HttpServletRequest request,
			HttpServletResponse response, PrintWriter out) {


		UploadedFile uploadedFile = uploadService.uploadFileTempDir(file);// 上传到临时目录

//		int width = Integer.valueOf(request.getParameter("width"));
//
//
//		// 缩率图
//		ImageUtils.scale(
//				uploadedFile.getUploadFullPath(),
//				uploadService.getUploadTempRootDir() + uploadedFile.getUploadSubDir()
//						+ FileUtils.fileNameAddSuffix(uploadedFile.getFileUploadedName(), SCALE), width);
//
		JSONObject obj = new JSONObject();

		obj.put("uploadedSubDir", uploadedFile.getUploadSubDir());// 子目录
		obj.put("originalFileUploadedName", uploadedFile.getFileUploadedName());// 原始文件上传之后的文件名
		obj.put("originalFileUploadedFullPath", uploadedFile.getUploadFullPath());// 原始文件上传之后的文件名
//		obj.put("scalePictureUrl",
//				uploadService.getUploadTempUrl() + uploadedFile.getUploadSubDir()
//						+ FileUtils.fileNameAddSuffix(uploadedFile.getFileUploadedName(), SCALE));// 缩率图读取url

		obj.put("error", 0);

		out.println(obj.toString());
		out = null;

	}


	/**
	 * 上传图片，向iframe提交
	 * <p>
	 *
	 * @param image
	 * @param request
	 * @return
	 */
	@RequestMapping(value = { "/upload-to-iframe" })
	@ResponseBody
	public void imageUploadToIframe(@ModelAttribute("imageUpload") ImageUploadToFrame imageUpload,
			HttpServletRequest request, PrintWriter out) {
		UploadedFile uploadedFile = uploadService.uploadFileTempDir(imageUpload.getFile());// 上传到临时目录

		String filePath = null;
		if (imageUpload.getMaxSize() > 0) {
			filePath = uploadedFile.getUploadSubDir()
					+ FileUtils.fileNameAddSuffix(uploadedFile.getFileUploadedName(), SCALE);
			ImageUtils.scale(uploadedFile.getUploadFullPath(), uploadService.getUploadRootDir() + filePath,
					imageUpload.getMaxSize());

		} else {
			filePath = uploadedFile.getUploadSubPath();
		}

		filePath = filePath.replace(File.separator, "/");
		String fileUrl = uploadService.getUploadUrl() + filePath;

		out.println("<script type=\"text/javascript\">parent.uploadSuccess('" + fileUrl + "', '" + filePath
				+ "');</script>");
	}
	
	/**
	 * @Description: ueditor图片上传
	 * @param upfile
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception String  
	 * @throws
	 * @author liu_wenfeng
	 * @date 2015年4月24日 下午2:44:55
	 */
	@RequestMapping("/upload/ueditor-images")
	@ResponseBody
	public String upload(@RequestParam("upfile") MultipartFile upfile,
			HttpServletRequest request, HttpServletResponse response) throws Exception {
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		String result = "";
		try {
			//{"name":"10571402926855858.jpg", "originalName": "china.jpg", "size": 43086, "state": "SUCCESS", "type": ".jpg", "url": "upload/20140616/10571402926855858.jpg"}
			// result返回的url参照IndexController._file方法
			String uploadFirstSubDir = "ueditor-accessory";
			UploadedFile uploadedFile = uploadService.uploadFileToUploadDir(uploadFirstSubDir, upfile);
			String url = uploadService.getUploadUrl() + uploadedFile.getReadUrl();
			result = "{\"name\":\""+ uploadedFile.getFileUploadedName() 
					+"\", \"originalName\": \""+ uploadedFile.getFileOriginalName() 
					+"\", \"size\": "+ upfile.getSize() 
					+", \"state\": \"SUCCESS\", \"type\": \""+ getFileExt(uploadedFile.getFileUploadedName())
					+"\", \"url\": \""+url+"\"}";
			result = result.replaceAll( "\\\\", "\\\\" );
		} catch(Exception e) {
			e.printStackTrace();
		}
		return result;
	}
	
	private String getFileExt(String fileName) {
		return fileName.substring(fileName.lastIndexOf("."));
	}
		

}
